<script>
	import store from 'store/index.js';
	import util from 'utils/utils.js';
	import * as api from '@/api/login';
	import request from '@/utils/httpRequset/js_sdk/request'
	// import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'

	// 引入原生插件
	// const pushLive = uni.requireNativePlugin('service-keep-live');

	var totaldata = new Array();
	var impedance = new Array(); //阻抗报文数组（80个字节长度）
	var bloodL = new Array(); //左脑血流报文（2000个字节长度）
	var bloodR = new Array(); //右脑血流报文（2000个字节长度）
	export default {
		globalData: {
			statusBarHeight: 47, //状态栏高度
			devices: [], //搜索到的ei设备列表
			deviceId: '',
			serviceId: '',
			characteristicId: '',
			data: '235',
			testname: 'zjj',
			count1: 0,
			boundRect_top: 53, //胶囊的上边距
			platform: '', //...
			notOperatedCount: 0, //规定时间内未操作断开连接
			operationTimer: null,
			lastDeviceId: '', //记录上次连接时的id
			isDeteDeviceState: false, //是否要检测设备的状态
		},
		onLaunch: function() {
			console.log('App Launch');
			let that = this;
			// #ifdef MP-WEIXIN
			const bound = wx.getMenuButtonBoundingClientRect();
			that.globalData.boundRect_top = bound.top;
			// #endif
			uni.getSystemInfo({
				success(res) {
					console.log('1: system platom>>', res);
					try {
						that.globalData.statusBarHeight = res.statusBarHeight;
						//将设备的UUID存入store中
						that.$store.commit('deviceUUID', res.deviceId);
						// 判断手机操作系统  开启服务
						that.globalData.platform = res.platform;
					} catch (e) {
						// error
					}
				}
			});
			try {
				const value = uni.getStorageSync('userInfo');
				if (value) store.commit('userInfo', value);
			} catch (e) {
				// error
				console.log('error', e);
			};
			// 监听网络情况  ..首次先检查
			uni.getNetworkType({
				success(res) {
					console.log(res);
					if (res.networkType == 'none') {
						store.commit('changeNetStatus', false);
						uni.showToast({
							title: '请检查网络连接',
							icon: 'none',
							duration: 3000
						});
					}
				}
			});
			// listening net state...
			uni.onNetworkStatusChange(function(res) {
				store.commit('changeNetStatus', res.isConnected);
				if (!res.isConnected) {
					uni.showToast({
						title: '请检查网络连接',
						icon: 'none',
					});
				}
			})
		},
		onShow: function() {
			console.log('App Show');
		},
		onHide: function() {
			console.log('App Hide');
		},
		methods: {
			getErpToken() {
				return new Promise((resolve, reject) => {
					let that = this;
					let data = {
						action: "getToken",
						params: {
							userName: 'annoyFree',
							userSecret: '123456'
						}
					};
					api.getToken(data).then(function(res) {
						if (res.data.code == 2000) {
							resolve(res.data.data.token);
						} else {
							reject(false);
						}
					}).catch(function(error) {
						reject(false);
						console.log('get Erp TokenId fail', error);
					});
				})
			},
			// 保活
			goStartService() {
				console.log('toservice');
				// wakeLock.wakeLock();
				let obj = {
					title: '免烦脑',
					content: '正在后台运行',
					mode: 1,
					isShow: true
				};
				pushLive.startService(obj, function(res) {
					console.log('开始服务', res);
				});
			},
			//以轮询的方式获取tokenId
			getTokenIdPolling() {
				this.getTokenId();
				let Timer = setInterval(this.getTokenId, 600000);
			},

			getTokenId() {
				let that = this;
				let userInfo = store.state.userInfo;
				let currentUser = userInfo.currentUser;
				let appId = currentUser.appId;
				let appSecret = currentUser.appSecret;
				let userId = currentUser.userId;
				// console.log('appId',appId);
				let data = {
					action: "getToken",
					userId: userId,
					params: {
						appId: appId,
						appSecret: appSecret
					}
				};
				api.getToken(data).then(function(res) {
						// console.log(res);
						if (res.data.code == 2000) {
							uni.setStorage({
								key: 'tokenId',
								data: res.data.code.token,
								success(res) {
									console.log('缓存成功 tokenId');
								}
							});
						} else if (res.data.code == 2001) {
							that.$toast('身份信息已过期，请重新登录');
							// 此处加一个强制退出功能
							let t = setTimeout(() => {
								clearTimeout(t);
								uni.reLaunch({
									url: '/pages/index/index.vue'
								})
							}, 2000);
						}
					})
					.catch(function(error) {
						console.log('get TokenId fail', error);
					});
			},
			async requestAgain(url, data) {
				console.log('token 过期,重新请求!');
				try {
					let res = await this.getTokenAgain();
					if (res) return request.post(url, data);
				} catch (e) {
					//TODO handle the exception
				}
			},
			getTokenAgain() {
				return new Promise((resolve, reject) => {
					let that = this;
					let appId = store.state.userInfo.currentUser.appId;
					let appSecret = store.state.userInfo.currentUser.appSecret;
					let userId = store.state.userInfo.currentUser.userId;
					let data = {
						action: "getToken",
						userId: userId,
						params: {
							appId: appId,
							appSecret: appSecret
						}
					};
					api.getToken(data).then(function(res) {
						// console.log(res);
						if (res.data.code == 2000) {
							store.commit('token', res.data.data.token);
							resolve(true);
						} else {
							reject(false);
						}
					}).catch(function(error) {
						reject(false);
						console.log('get TokenId fail', error);
					});
				})
			},
			//弹窗
			showToast(icon, title) {
				uni.showToast({
					title: title,
					icon: icon
				});
			},
			/*
			 * 退出登录：清除缓存中所有信息、清除 store中的个人信息
			 */
			exitLogin() {
				try {
					// this.$toast('此操作不可逆 会删除缓存中得所有信息',{duration:3000});
					uni.clearStorageSync();
					store.commit('userInfo', null);
					//判断蓝牙连接状态
					if (store.state.isConnected) app.closeBluetoothAdapter();;
					let T = setTimeout(() => {
						clearTimeout(T);
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}, 1000)
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			/**
			 * 蓝牙相关的代码 。。。
			 */
			openBluetoothAdapter1(obj) {
				uni.openBluetoothAdapter({
					success: res => {
						// console.log('开启适配器成功');
						uni.getBluetoothAdapterState({
							success: res1 => {
								// console.log(res1, '蓝牙已打开');
								this.createBLEConnection(obj);
							},
							fail(error) {
								this.showToast('none', '请检查手机蓝牙是否打开!');
							}
						});
					},
					fail: err => {
						// console.log('适配器开启失败!');
						this.showToast('none', '请检查手机蓝牙是否打开!');
					}
				});
				this.onBluetoothAdapterStateChange();
			},
			writeBLEState(type) {
				console.log('当前的type值: ',type)
        return new Promise((resolve, reject) => {
          if (!store.state.isConnected) return resolve(false);
          console.log('send msg type: ', type);
          store.commit('receiptTimer', 0);

          let buffer = new ArrayBuffer(7);
          let dataView = new DataView(buffer);
          dataView.setUint8(0, 0x68);
          dataView.setUint8(1, 0x00);
          dataView.setUint8(2, 0x07);
          switch (type) {
            case 1: //开始快速
              dataView.setUint8(3, 0x01);
              dataView.setUint8(4, 0x45);
              dataView.setUint8(5, 0x2a);
              break;
            case 2: // 退出快速
              dataView.setUint8(3, 0x02);
              dataView.setUint8(4, 0x75);
              dataView.setUint8(5, 0x49);
              break;
            case 3: //深度监测
              dataView.setUint8(3, 0x03);
              dataView.setUint8(4, 0x65);
              dataView.setUint8(5, 0x68);
              break;
            case 10: //获取头环版本号
              dataView.setUint8(3, 0x10);
              dataView.setUint8(4, 0x47);
              dataView.setUint8(5, 0x3a);
              break;
            case 15: //获取头环电量
              dataView.setUint8(3, 0x0F);
              dataView.setUint8(4, 0xa4);
              dataView.setUint8(5, 0xe4);
              break;
            case 20:
              dataView.setUint8(3, 0x20);
              dataView.setUint8(4, 0x71);
              dataView.setUint8(5, 0x69);
              break;
            case 23:
              dataView.setUint8(3, 0x23);
              dataView.setUint8(4, 0x41);
              dataView.setUint8(5, 0x0A);
              break;
            case 24:
              dataView.setUint8(3, 0x24);
              dataView.setUint8(4, 0x31);
              dataView.setUint8(5, 0xED);
              break;
            case 25: //滴滴2声音
              dataView.setUint8(3, 0x25);
              dataView.setUint8(4, 0x21);
              dataView.setUint8(5, 0xCC);
              break;
            case 26://滴滴滴3声音
              dataView.setUint8(3, 0x26);
              dataView.setUint8(4, 0x11);
              dataView.setUint8(5, 0xAF);
              break;
            case 29: //头环佩戴状态
              dataView.setUint8(3, 0x29);
              dataView.setUint8(4, 0xE0);
              dataView.setUint8(5, 0x40);
              break;
          }
          dataView.setUint8(6, 0x16);
          this.writeBLECharacteristicValue(buffer)

          if(type === 10) return;
          console.log("isReceipt",store.state.isReceipt)
          store.state.receiptTimer = setTimeout(() =>{
            if(!store.state.isConnected) return resolve(false);
            if(!store.state.isReceipt) {
              console.log('未收到回执数据--',type);
              uni.showToast({
                title:'与头环通信失败，请重启设备',
                icon: 'none'
              });
              clearTimeout(store.state.receiptTimer);
              store.commit('receiptTimer', null);
              return resolve(true);
            }else{
              store.commit('isReceipt',false);
              clearTimeout(store.state.receiptTimer);
              store.commit('receiptTimer',null);
              return resolve(true);
            }
          },1000)
        })

			},
			// 开启蓝牙适配器
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: res => {
						// console.log('开启适配器成功');
						uni.getBluetoothAdapterState({
							success: res1 => {
								// console.log(res1, '蓝牙已打开');
								this.onBluetoothAdapterStateChange();
								//开始搜索设备
								this.startBluetoothDeviceDiscovery();
							},
							fail(error) {
								this.showToast('none', '请检查手机蓝牙是否打开!');
							}
						});
					},
					fail: err => {
						console.log('适配器开启失败!');
						store.commit('BluetoothAdapterState', false);
					}
				});
			},
			// 监听蓝牙适配器状态
			onBluetoothAdapterStateChange() {
				uni.onBluetoothAdapterStateChange(function(res) {
					// console.log('adapterState changed, now is', res.available);
					store.commit('BluetoothAdapterState', res.available);
				});
			},
			//开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
				console.log('开始搜索');
				uni.startBluetoothDevicesDiscovery({
					services: ['6E40FFF0-B5A3-F393-E0A9-E50E24DCCA9E'], // 限定主service的uuid
					success: res => {
						// console.log('startBluetoothDeviceDiscovery  success', res);
						// this.getBluetoothDevices();
						this.onBluetoothDeviceFound();
					},
					fail: res => {
						console.log('开始搜索蓝呀失败');
					}
				});
			},
			// 获取蓝牙设备列表
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						// console.log('获取蓝牙设备成功1:' + res);
						console.log(JSON.stringify(res));
					},
					fail: e => {
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			//检测蓝牙设备状态  安卓设备需要先重启蓝牙适配器
			deteDeviceState(flag) {
				this.globalData.isDeteDeviceState = flag
				if (this.globalData.platform == 'android') {
					this.reStartBleAdapter()
				} else {
					this.startBluetoothDeviceDiscovery()
				}
			},
			reStartBleAdapter() {
				let that = this
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('closeBluetoothAdapter success', res);
						uni.openBluetoothAdapter({
							success: res => {
								that.startBluetoothDeviceDiscovery()
							},
							fail: err => {
								console.log('适配器开启失败!');
								store.commit('BluetoothAdapterState', false);
							}
						});
					},
					fail(res) {
						console.log('closeBluetoothAdapter fail', res);
					}
				});
			},

			// 发现外围设备（监听）
			onBluetoothDeviceFound() {
				var that = this;
				var timer = null;
				var serachDeviceName = 'EI-B100_39e9957d78587fe';
				uni.onBluetoothDeviceFound(res => {
					// console.log('发现的蓝牙设备', res);
					if (res.devices.length != 0) {
						res.devices.forEach(device => {
							if (device.name.indexOf(serachDeviceName) != -1) {
								console.log('EI的设备', device.name);
								that.globalData.devices.push(device);
							}
						});

            console.log("99999999999",that.globalData.devices)
					}
				});
				//成功与否，都关闭蓝牙搜索
				timer = setTimeout(() => {
					console.log('倒计时结束 停止搜索');
					that.stopBluetoothDevicesDiscovery();
					clearTimeout(timer);
					// 这里做一些搜索不到设备的操作 延时
				}, 3000);
			},
			// 关闭蓝牙扫描状态
			stopBluetoothDevicesDiscovery() {
				let that = this;
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log('stopBluetoothDevicesDiscovery  success ', res);
						if (that.globalData.isDeteDeviceState) {
							let findDevices = []
							that.globalData.devices.forEach((item) => {
								findDevices.push(item.deviceId)
							})
							if (findDevices.indexOf(that.globalData.lastDeviceId) == -1) {
								uni.$emit('ble-device-state', {
									msg: '设备已关机'
								})
							} else {
								uni.$emit('ble-device-state', {
									msg: '连接已断开'
								})
							}
							return
						}
						if (that.globalData.devices.length == 1) {
							that.createBLEConnection(that.globalData.devices[0]);
              store.commit("setDfuDevices",that.globalData.devices[0])
							store.commit('isEiDevice', true);
						} else if (that.globalData.devices.length > 1) {
							console.log('搜索到多个EI的设备，？？？？？');
							uni.showToast({
								title: '发现多个设备',
								icon: 'none'
							});
						} else {
							console.log('没找到EI的设备!!!');
							store.commit('isEiDevice', false);
						}
					},
					fail(res) {
						console.log('stopBluetoothDevicesDiscovery  fail!! ');
					}
				});
			},
			//建立连接
			createBLEConnection(device) {
				let that = this;
				let deviceId = device.deviceId;
				uni.createBLEConnection({
					deviceId,
					success(res) {
						console.log('connected success', res);
						that.getBLEDeviceServices(deviceId);
					},
					fail(res) {
						console.log('connected fail', res);
					}
				});
				console.log('在此处监听蓝牙的连接状态');
				//在此处监听蓝牙的连接状态  该方法回调中可以用于处理连接意外断开等异常情况
				uni.onBLEConnectionStateChange(function(res) {
					console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
					if (!res.connected) {
						that.globalData.devices = [];
					}
					that.globalData.lastDeviceId = res.deviceId

					store.commit('connectState', res.connected);
				});
			},
			// 获取蓝牙的服务
			getBLEDeviceServices(deviceId) {
				let that = this;
				var timer = setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							console.log('getBLEDeviceServices success', res);
							res.services.forEach(service => {
								if (service.uuid.indexOf('6E40FFF0') != -1) {
									// 在此处开启数据监听 （接收）
									uni.onBLECharacteristicValueChange(res => {
										console.log('监听到的蓝牙数据>>>>>'+res.value);
										uni.$emit('originalData', {
											msg: res.value
										});
										//直接将数据给store
										store.commit('originalData', res.value);
									});
									that.getBLEDeviceCharacteristics(deviceId, service.uuid);
									return;
								}
							});
						},
						fail(res) {
							console.log('getBLEDeviceServices fail!!!', res);
						}
					});
					clearTimeout(timer);
				}, 2000);
			},

			// 获取蓝牙特征值
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				let that = this;
				console.log('获取蓝牙特征值1', serviceId);
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success(res) {
						console.log('getBLEDeviceCharacteristics success', res);
						res.characteristics.forEach(characteristic => {
							if (characteristic.properties.read) {
								uni.readBLECharacteristicValue({
									characteristicId: characteristic.uuid,
									deviceId,
									serviceId
								});
							}
							if (characteristic.properties.notify || characteristic.properties.indicate) {
								uni.notifyBLECharacteristicValueChange({
									state: true,
									deviceId,
									serviceId,
									characteristicId: characteristic.uuid,
									success(res) {
										// console.log('notifyBLECharacteristicValueChange success', res);
									}
								});
							}
							if (characteristic.properties.write) {
								that.globalData.deviceId = deviceId;
								that.globalData.serviceId = serviceId;
								that.globalData.characteristicId = characteristic.uuid;

                // 以下都有问题
								let timer = setTimeout(() => {
                  clearTimeout(timer);
									that.writeBLEState(10)
								}, 800);

							}
						});
					},
					fail(res) {
						console.log('getBLEDeviceCharacteristics fail', res);
					}
				});
			},
			writeBLECharacteristicValue(value) {
				let that = this;
        that.globalData.notOperatedCount = 0
				uni.writeBLECharacteristicValue({
					deviceId: that.globalData.deviceId,
					serviceId: that.globalData.serviceId,
					characteristicId: that.globalData.characteristicId,
					value: value,
					success(res) {
						// console.log('writeBLECharacteristicValue success', res);
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res);
					}
				});
			},
			closeBLEConnection() {
				let deviceId = this.globalData.deviceId;
				uni.closeBLEConnection({
					deviceId: deviceId,
					success(res) {
						store.commit('isActiveDisConnect', true)
						console.log('closeBleConnection  success!!', res);
					},
					fail(err) {
						console.log('closeBleConnection  fail!!', err);
					}
				})
			},
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('closeBluetoothAdapter success', res);
					},
					fail(res) {
						console.log('closeBluetoothAdapter fail', res);
					}
				});
			},
		}
	};
</script>

<style>
	/*每个页面公共css */
</style>